<?php
/**
 * Created by PhpStorm.
 * User: william
 * Date: 16-5-26
 * Time: 下午3:26
 */

define( 'CLASS_DIR' , dirname(dirname(__FILE__)).'/Orm/');
define( 'TEMP_DIR' , dirname(__FILE__).'/Template/');

class makeCls{

    private $dbhost = '192.168.10.65';//'renrencaichangdbv2.mysql.rds.aliyuncs.com';//'db.dev.renrencaichang.com';
    private $dbuser = 'rrcc';
    private $dbpass = 'renrenc@ich@ng';//'renrencaichang1';

    private $cls_name = '';
    private $table_name = '';
    private $columns = '';
    private $schema_name = 'shanguang';

    function __construct($class_name)
    {
        header("Content-Type: application/json; charset=utf-8");
        $this->cls_name = ucfirst($class_name);
        $this->table_name = strtolower('t'.preg_replace('@([A-Z])@','_$1',$this->cls_name));
        $this->class_dir = CLASS_DIR.$this->cls_name.'/';

        if (is_dir($this->class_dir)) {
            fwrite(STDOUT,"{$this->cls_name} 已存在，确认要覆盖它吗？(Y or N) ");
            $stdin = fgets(STDIN);
            if (trim($stdin) !== 'Y') {
                exit;
            }
        } else {
            system("mkdir {$this->class_dir}");
        }
    }

    function run()
    {
        $this->makeClassFile();
        $this->makeListFile();
        $this->makeModelFile();
        $this->makeTestFile();
        echo "Class {$this->cls_name} has make done.\n";
    }

    private function getColumns()
    {
        $columns = array();
        $mysql_link = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
        mysql_query('set names utf8;',$mysql_link);

        $sql = "SELECT
                    table_schema AS `Schema`,
                    column_name AS `Field`,
                    data_type AS `Type`,
                    column_comment AS `Memo`
                FROM
                    Information_schema.columns
                WHERE
                    table_Name = '{$this->table_name}';";
        $query = mysql_query($sql);
        for($i=0;$i< mysql_num_rows($query) ;$i++)
        {
            $rows = mysql_fetch_assoc($query);
            if ($rows['Schema'] != $this->schema_name) continue;
            $columns[] = $rows;
        }
        if (count($columns)  ==0) exit("数据库中未找到此表。");
        return $columns;
    }

    private function makeColumnsText()
    {
        $text = '';
        $this->columns = $this->getColumns();
        $column_cnt = count($this->columns);
        foreach ($this->columns as $key=>$column) {
            if ($column['Field'] == 'id') {
                $text .= "\${$column['Field']},\n";
                continue;
            }
            if ($key == $column_cnt-1) $sign = ';';
            else $sign = ',';
            if ($key == $column_cnt-1) $br = "";
            else $br = "\n";
            if (strpos($column['Type'],'int') !== false || strpos($column['Type'],'decimal') !== false) {
                $text .= "\t\t\t\t\${$column['Field']} = 0{$sign}";
            } else {
                $text .= "\t\t\t\t\${$column['Field']} = ''{$sign}";
            }
            $memo = preg_replace('@\n@','',$column['Memo']);
            if ($column['Memo']) $text .= " // {$memo}";
            $text .=$br;
        }
        return $text;
    }

    private function makeKeysText()
    {
        $text = '';
        $this->columns = $this->getColumns();
        foreach ($this->columns as $column) {
            if ($column['Field'] == 'id'
                || $column['Field'] == 'insert_time'
                || $column['Field'] == 'update_time'
                || $column['Field'] == 'is_del') continue;
            $text .= "\t\t\t'{$column['Field']}' => \$this->{$column['Field']},\n";
        }
        $text = substr($text,3);
        $text = substr($text,0,-1);
        return $text;
    }

    private function makeClassFile()
    {
        $columns_text = $this->makeColumnsText();
        $keys_text = $this->makeKeysText();
        $temp_class_text = file_get_contents(TEMP_DIR.'Class.temp');
        $new_class_text = str_replace("__COLUMNS__",$columns_text,$temp_class_text);
        $new_class_text = str_replace("__KEYS__",$keys_text,$new_class_text);
        $new_class_text = str_replace("__CLASSNAME__",$this->cls_name,$new_class_text);
        file_put_contents($this->class_dir.$this->cls_name.'Class.php',$new_class_text);
    }

    private function makeListFile()
    {
        $temp_class_text = file_get_contents(TEMP_DIR.'List.temp');
        $new_class_text = str_replace("__CLASSNAME__",$this->cls_name,$temp_class_text);
        file_put_contents($this->class_dir.$this->cls_name.'List.php',$new_class_text);
    }

    private function makeModelFile()
    {
        $temp_class_text = file_get_contents(TEMP_DIR.'Model.temp');
        $new_class_text = str_replace("__CLASSNAME__",$this->cls_name,$temp_class_text);
        $new_class_text = str_replace("__TABLENAME__",$this->table_name,$new_class_text);
        file_put_contents($this->class_dir.$this->cls_name.'Model.php',$new_class_text);
    }

    private function makeTestFile()
    {
        $temp_class_text = file_get_contents(TEMP_DIR.'Test.temp');
        $test_key_text = $this->makeTestKeyText();
        $test_equals_text = $this->makeTestEquals();

        $new_class_text = str_replace("__CLASSNAME__",$this->cls_name,$temp_class_text);
        $new_class_text = str_replace("__TESTKEY__",$test_key_text,$new_class_text);
        $new_class_text = str_replace("__TESTEQUALS__",$test_equals_text,$new_class_text);
        file_put_contents($this->class_dir.$this->cls_name.'Test.php',$new_class_text);
    }

    private function makeTestKeyText()
    {
        $text = '';
        $this->columns = $this->getColumns();
        foreach ($this->columns as $key=>$column) {
            if ($column['Field'] == 'id'
                || $column['Field'] == 'insert_time'
                || $column['Field'] == 'update_time'
                || $column['Field'] == 'is_del') continue;
            if (strpos($column['Type'],'int') !== false ||strpos($column['Type'],'decimal') !== false) {
                if (strpos($column['Type'],'is_') !== false) {
                    $text .= "\t\t\$class['{$column['Field']}'] = \$this->testBoolean();";
                } else {
                    $text .= "\t\t\$class['{$column['Field']}'] = \$this->testNum();";
                }
            } else {
                $text .= "\t\t\$class['{$column['Field']}'] = \$this->testStr();";
            }
            $text .="\n";
        }
        return $text;
    }
    private function makeTestEquals()
    {
        $text = '';
        $this->columns = $this->getColumns();
        foreach ($this->columns as $key=>$column) {
            if ($column['Field'] == 'id'
                || $column['Field'] == 'insert_time'
                || $column['Field'] == 'update_time'
                || $column['Field'] == 'is_del') continue;
            $text .= "\t\t\$this->assertEquals(\$class['{$column['Field']}'],\$result_class['{$column['Field']}']);";
            $text .="\n";
        }
        return $text;
    }
}

$makeCls = new makeCls($argv[1]);
$makeCls->run();
exit;